import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Random;
import java.util.RandomAccess;

/**
 * Created by root on 17-6-6.
 */


public class FileChannelDemo1 {
    public static void main(String[] args) throws IOException {
        /*文件NIO
             增强文件操作,可以从文件中间取数据,下面是读数据的例子
             root@user-pc:/home/user# cat 1.txt
             javacaonima

        */

        FileInputStream in = new FileInputStream("/home/user/1.txt");
        FileChannel channel = in.getChannel();

        channel.position(4);
        ByteBuffer temp = ByteBuffer.allocate(3);

        channel.read(temp);
        String str = new String(temp.array());
        System.out.println(str);
        channel.close();
        /*
            下面是写数据的例子
         */

        RandomAccessFile raf = new RandomAccessFile("/home/user/1.txt","rw");   //这么做不会修改其他的数据，只修改你要修改的数据
    //    FileOutputStream out = new FileOutputStream("/home/user/1.txt");
        FileChannel channel2 = raf.getChannel();
        channel2.position(4);
        channel2.write(ByteBuffer.wrap("gan".getBytes()));
        channel2.close();

    }
}
